//导入路由器
import { createRouter, createWebHistory } from "vue-router";
import { useTokenStore } from "@/stores/token";
import { ElMessage } from "element-plus";
import useUserInfoStore from "@/stores/userInfo";

//导入组件
import LoginVue from "@/views/Login.vue";
import Daily from "@/views/Daily.vue";
import Picture from "@/views/Picture.vue";
import Video from "@/views/Video.vue";

//定义路由关系
const routes = [
  { path: "/", redirect: "/login" },
  {
    path: "/login",
    component: LoginVue,
    meta: {
      title: "登录",
    },
  },
  {
    path: "/daily",
    name: "Daily",
    component: Daily,
    meta: {
      requiresAuth: true,
      title: "主页",
    },
  },
  {
    path: "/picture",
    name: "Picture",
    component: Picture,
    meta: {
      requiresAuth: true,
      title: "图片",
    },
  },
  {
    path: "/video",
    name: "Video",
    component: Video,
    meta: {
      requiresAuth: true,
      title: "视频",
    },
  },
  {
    path: "/upload",
    name: "upload",
    component: () => import("@/views/Upload.vue"),
    meta: {
      requiresAuth: true,
      title: "上传",
    },
  },
];

//创建路由器
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: routes,
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition;
    } else {
      return { top: 0 };
    }
  },
});

// 添加导航守卫
router.beforeEach(async (to, from, next) => {
  // 设置页面标题
  document.title = to.meta.title || "日记本";

  // 在路由守卫内部初始化store
  const tokenStore = useTokenStore();
  const userInfoStore = useUserInfoStore();

  console.log("路由跳转:", {
    from: from.path,
    to: to.path,
    hasToken: tokenStore.hasToken(),
  });

  // 如果是访问登录页面
  if (to.path === "/login") {
    // 清除旧的登录信息
    userInfoStore.removeInfo();
    tokenStore.removeToken();
    console.log("访问登录页面，已清除登录信息");
    next();
    return;
  }

  // 需要登录的页面
  if (to.meta.requiresAuth) {
    if (!tokenStore.hasToken()) {
      console.log("未登录，重定向到登录页");
      ElMessage.warning("请先登录");
      next("/login");
      return;
    }

    try {
      const isValid = await tokenStore.validateToken();
      if (!isValid) {
        console.log("Token无效，重定向到登录页");
        ElMessage.warning("登录已过期，请重新登录");
        userInfoStore.removeInfo();
        tokenStore.removeToken();
        next("/login");
        return;
      }
      console.log("Token验证通过，允许访问:", to.path);
      next();
    } catch (error) {
      console.error("Token验证失败:", error);
      ElMessage.error("登录状态异常，请重新登录");
      userInfoStore.removeInfo();
      tokenStore.removeToken();
      next("/login");
    }
  } else {
    next();
  }
});

// 路由切换后
router.afterEach((to, from) => {
  // 关闭所有加载状态
  const loading = document.querySelector(".el-loading-mask");
  if (loading) {
    loading.remove();
  }
});

//导出路由
export default router;
